package com.sws.common.utils.access_tokenutil.controller;


import com.sws.common.utils.access_tokenutil.model.DeviceToken;

import com.sws.common.utils.access_tokenutil.service.IAccessTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 访问令牌控制器
 */
@Api(tags = {"访问令牌控制器"})
@Slf4j
@RestController
@RequestMapping("/api/token")
public class TokenController {

    @Autowired
    private IAccessTokenService accessTokenService;

    /**
     * 获取设备访问令牌
     *
     * @param deviceIp 设备IP地址
     * @return 设备访问令牌信息
     */
    @ApiOperation("获取设备访问令牌")
    @GetMapping("/{deviceIp}")
    public ResponseEntity<DeviceToken> getAccessToken(@PathVariable String deviceIp) {
        log.info("获取设备[{}]的访问令牌", deviceIp);
        DeviceToken deviceToken = accessTokenService.getAccessToken(deviceIp);
        if (deviceToken != null) {
            return ResponseEntity.ok(deviceToken);
        } else {
            return ResponseEntity.notFound().build();
        }
    }



    /**
     * 仅获取设备访问令牌字符串
     *
     * @param deviceIp 设备IP地址
     * @return 访问令牌字符串
     */
    @ApiOperation("仅获取设备访问令牌字符串")
    @GetMapping("/string/{deviceIp}")
    public ResponseEntity<String> getToken(@PathVariable String deviceIp) {
        log.info("获取设备[{}]的访问令牌字符串", deviceIp);
        String token = accessTokenService.getToken(deviceIp);
        if (token != null) {
            return ResponseEntity.ok(token);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 刷新设备访问令牌
     *
     * @param deviceIp 设备IP地址
     * @return 刷新结果
     */
    @ApiOperation("刷新设备访问令牌")
    @GetMapping("/refresh/{deviceIp}")
    public ResponseEntity<String> refreshAccessToken(@PathVariable String deviceIp) {
        log.info("手动刷新设备[{}]的访问令牌", deviceIp);
        boolean result = accessTokenService.refreshAccessToken(deviceIp);
        if (result) {
            return ResponseEntity.ok("刷新成功");
        } else {
            return ResponseEntity.badRequest().body("刷新失败");
        }
    }

    /**
     * 刷新所有设备的访问令牌
     *
     * @return 刷新结果
     */
    @ApiOperation("刷新所有设备的访问令牌")
    @GetMapping("/refresh/all")
    public ResponseEntity<String> refreshAllAccessTokens() {
        log.info("手动刷新所有设备的访问令牌");
        accessTokenService.refreshAllAccessTokens();
        return ResponseEntity.ok("刷新任务已启动");
    }
} 